# -*- coding: utf-8 -*-
from VideoCapture import Device
from PIL import Image,ImageDraw
import sys
import pygame
import win32api
import time
import random
import libgmail

turret = random.randint(1,6)
fileHandle = open ( 'config.cfg' )
exec(fileHandle.read())
fileHandle.close() 

def diff_image(img1, img2, pix_threshold=50, img_threshold=10):
    """ Compare 2 images to detect possible motion """
    if not img1 or not img2: return False
    img1 = img1.getdata()
    img2 = img2.getdata()
    pixel_count = len(img1)
    pixdiff = 0
    for i in range(pixel_count):
        if abs(sum(img1[i]) - sum(img2[i])) > pix_threshold:
            pixdiff += 1
            diffperc = pixdiff / (pixel_count/100)
            if diffperc > img_threshold:
                # motion detected
                return True

# init pygame
pygame.init()
#fileHandle = open ( 'config.cfg' )
#exec(fileHandle.read())
#fileHandle.close() 
#width = int(width)
#height = int(height)

# setup screen size



# get cam device
cam = Device()

cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
im = Image.open("image.jpg")
width = im.size[0]
height = im.size[1]
size = width, height

screen = pygame.display.set_mode(size)
left_button = None
right_button = None
while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    camshot = cam.getImage()

    # process left button
    new_left_button = camshot.crop((20,20,width-20,height-20))
    draw = ImageDraw.Draw(camshot)
    if diff_image(left_button, new_left_button):
        draw.rectangle((20,20,width-20,height-20), fill=128)
        ga = libgmail.GmailAccount('portal.turret.glados', '')
        ga.login()
        cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
        nfile = 'image.jpg'
        gmsg = libgmail.GmailComposedMessage(email, 'I...SEE...YOU', ' ',filenames=[nfile])
        ga.sendMessage(gmsg)
        soundturret = 'turret%s.wav'%str(turret)
        sound=pygame.mixer.Sound(soundturret)
        turret = random.randint(1,6)
        channel=sound.play()
        time.sleep(10)
        #while channel.get_busy():
               #pygame.time.wait(10)
        
        

        #win32api.ShellExecute(0,'open','chocolat.mp3',None,'',1)
    else:
        draw.rectangle((20,20,width-20,height-20), outline=128)
    left_button = new_left_button




    camshot = camshot.transpose(0)
    
    
    camshot = pygame.image.fromstring(camshot.tostring(), (width,height), "RGB")

    screen.blit(camshot, (0,0))
    pygame.display.flip()
